package com.eascs.admin.o2o.backFees.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.account.api.IFeeService;
import com.eascs.account.api.constants.enums.SourceType;
import com.eascs.account.api.constants.enums.TradeType;
import com.eascs.account.api.vo.TradeDetailVO;
import com.eascs.account.api.vo.TradeParamsVO;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.utils.AccountConstants;
import com.eascs.admin.o2o.backFees.dao.O2oBackFeesDao;
import com.eascs.admin.o2o.backFees.entity.O2oBackFeesEntity;
import com.eascs.admin.o2o.backFees.vo.O2oBackFeesVo;
import com.eascs.admin.o2o.detail.dao.OaDetailDao;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loanAccount.entity.AccountLog;
import com.eascs.admin.o2o.loanAccount.service.IAccountLogService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;

@Service
public class O2oBackFeesService extends BaseSevice {
	private final Logger logger = LoggerFactory.getLogger(O2oBackFeesService.class);
	@Autowired
	private O2oBackFeesDao o2oBackFeesDao;

	@Autowired
	BaseUserUtil userUtils;
	@Reference
	private WorkFlowService workFlowService;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	O2oLoanService o2oLoanService;
	@Autowired
	OaDetailDao oaDetailDao;

	@Reference
	private CustomerService customerService;

	@Reference
	private IFeeService iFeeService;

	@Autowired
	private IAccountLogService iAccountLogService;

	@Value("${o2o.admin.backfeeUrl}")
	private String backfeeUrl;

	public O2oBackFeesEntity queryEntity(String loanapplyNo, String billStatus) {
		String depositSql = "select * from o2o_back_fees t where t.loanapply_no=?";
		if (!StringUtil.isBlank(billStatus)) {
			depositSql = depositSql + "  and bill_status = '" + billStatus + "' ";
		}
		return o2oBackFeesDao.findEntity(depositSql, O2oBackFeesEntity.class, loanapplyNo.trim());
	}

	public O2oBackFeesEntity queryById(String id) {
		return o2oBackFeesDao.getById(O2oBackFeesEntity.class, id);
	}

	public int update(O2oBackFeesEntity o2oBackFeesEntity) {
		return o2oBackFeesDao.updateById(o2oBackFeesEntity);
	}

	public int insert(O2oBackFeesEntity o2oBackFeesEntity) {
		return o2oBackFeesDao.insert(o2oBackFeesEntity);
	}

	/**
	 * 个人退款-账户系统
	 * 
	 * @param O2oBackFeesVo
	 * @return
	 */
	public PageResult<Object[]> findByPage(O2oBackFeesVo vo) {
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, vo.getPageSize(), vo.getPageIndex() == null ? BaseUtils.PAGE_INDEX : vo.getPageIndex());
		StringBuffer sql = new StringBuffer();
		sql.append("select id,bill_code,create_name,ltd_name,loan_name,document_no,back_money,create_date,os.status  FROM 	o2o_back_fees os ");
		sql.append(" where  ");
		sql.append(" os.is_del = 'N'  ");
		if (UserHolder.getUser().isSuperAdministrator() || vo.isQueryAll()) {

		} else {
			sql.append(" and (os.create_id=" + UserHolder.getUser().getNo() + ")");
		}

		if (StringUtil.hasText(vo.getName())) {
			sql.append(" and os.loan_name like ?");
			pageQuery.addLikeParam(vo.getName());
		}

		if (StringUtil.hasText(vo.getIdCard())) {
			sql.append(" and os.document_no = ?");
			pageQuery.addParam(vo.getIdCard());
		}
		if (StringUtil.hasText(vo.getStatus())) {
			sql.append(" and os.status = ?");
			pageQuery.addParam(vo.getStatus());
		}
		if (StringUtil.hasText(vo.getLtdName())) {
			sql.append(" and os.ltd_name like ?");
			pageQuery.addLikeParam(vo.getLtdName());
		}
		if (StringUtil.hasText(vo.getCreateName())) {
			sql.append(" and os.create_name like ?");
			pageQuery.addLikeParam(vo.getCreateName());
		}

		if (StringUtil.hasText(vo.getCreateStartTime())) {
			sql.append(" and os.create_date >= ? ");
			pageQuery.addParam(vo.getCreateStartTime());
		}
		if (StringUtil.hasText(vo.getCreateEndTime())) {
			sql.append(" and os.create_date <= ? ");
			GregorianCalendar gc = new GregorianCalendar();
			gc.setTime(DateUtils.formateStandDate(vo.getCreateEndTime()));
			gc.add(5, 1);
			pageQuery.addParam(gc.getTime());
		}

		sql.append(" order by os.create_date	desc ");
		// pageQuery.setSumColumnIndexs(new int[]{10});
		pageQuery.setQuerySql(sql.toString());
		logger.info("findByPage,sql={}", sql.toString());
		return o2oBackFeesDao.findDataWithPage(pageQuery);
	}
	
	public PageResult<Object[]> findByPageExport(O2oBackFeesVo vo) {
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<Object[]>(Object[].class, vo.getPageSize(), vo.getPageIndex() == null ? BaseUtils.PAGE_INDEX : vo.getPageIndex());
		StringBuffer sql = new StringBuffer();
		sql.append("select bill_code,create_name,ltd_name,loan_name,document_no,back_money,DATE_FORMAT(back_date,'%Y-%m-%d'),back_no,back_sj_no,dd.item_name ");
		sql.append(",(case when os.status='NEW' then '新建' when os.status='RUN' then '审核中' when os.status='CLO' then '流程结束' end) ");
		sql.append(" FROM o2o_back_fees os LEFT JOIN pub_dditem dd on dd.item_code = back_type and dd.dd_no='136' ");
		sql.append(" where os.is_del ='N' ");
		if (UserHolder.getUser().isSuperAdministrator() || vo.isQueryAll()) {
			
		} else {
			sql.append(" and (os.create_id=" + UserHolder.getUser().getNo() + ")");
		}
		
		if (StringUtil.hasText(vo.getName())) {
			sql.append(" and os.loan_name like ?");
			pageQuery.addLikeParam(vo.getName());
		}
		
		if (StringUtil.hasText(vo.getIdCard())) {
			sql.append(" and os.document_no = ?");
			pageQuery.addParam(vo.getIdCard());
		}
		if (StringUtil.hasText(vo.getStatus())) {
			sql.append(" and os.status = ?");
			pageQuery.addParam(vo.getStatus());
		}
		if (StringUtil.hasText(vo.getLtdName())) {
			sql.append(" and os.ltd_name like ?");
			pageQuery.addLikeParam(vo.getLtdName());
		}
		if (StringUtil.hasText(vo.getCreateName())) {
			sql.append(" and os.create_name like ?");
			pageQuery.addLikeParam(vo.getCreateName());
		}
		
		if (StringUtil.hasText(vo.getCreateStartTime())) {
			sql.append(" and os.create_date >= ? ");
			pageQuery.addParam(vo.getCreateStartTime());
		}
		if (StringUtil.hasText(vo.getCreateEndTime())) {
			sql.append(" and os.create_date <= ? ");
			GregorianCalendar gc = new GregorianCalendar();
			gc.setTime(DateUtils.formateStandDate(vo.getCreateEndTime()));
			gc.add(5, 1);
			pageQuery.addParam(gc.getTime());
		}
		
		sql.append(" order by os.create_date	desc ");
		// pageQuery.setSumColumnIndexs(new int[]{10});
		pageQuery.setQuerySql(sql.toString());
		logger.info("findByPage,sql={}", sql.toString());
		return o2oBackFeesDao.findDataWithPage(pageQuery);
	}

	/**
	 * 冻结
	 * 
	 * @param type
	 * @return
	 */
	// @Transactional(transactionManager = "o2oTransactionManager")
	public String ChargingDJ(O2oBackFeesEntity o2oBackFees, String type) {
		AccountLog accountLog = new AccountLog();
		accountLog.setStartTime(new Date());
		accountLog.setId(UuidUtil.generateShortUuid());
		accountLog.setUniqueId(o2oBackFees.getUniqueId());
		CustomerEntity customerEntity = customerService.queryCustomerEntityByCustomerId(o2oBackFees.getLoanId());
		if (null == customerEntity.getAccountId()) {
			return "借款人个人账户未开户，请联系运维同事";
		}
		//
		TradeDetailVO recDeposite = new TradeDetailVO();// 封装保证金数据

		TradeParamsVO paramsVO = new TradeParamsVO();

		if (AccountConstants.ACCOUNT_DJ.equals(type)) {
			recDeposite.setTradeType(TradeType.REFUND_FROZEN);
			paramsVO.setBizType(AccountConstants.ACCOUNT_DJ);
			accountLog.setLogType(AccountConstants.ACCOUNT_DJ);
			recDeposite.setRemark("客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
			paramsVO.setRemark("冻结（个人账户退款）" + "客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
		}

		if (AccountConstants.ACCOUNT_JD.equals(type)) {
			recDeposite.setTradeType(TradeType.REFUND_UNFROZEN);
			paramsVO.setBizType(AccountConstants.ACCOUNT_JD);
			accountLog.setLogType(AccountConstants.ACCOUNT_JD);
			recDeposite.setRemark("客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
			paramsVO.setRemark("解冻（个人账户退款）" + "客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
		}

		if (AccountConstants.ACCOUNT_DJ_ZF.equals(type)) {
			recDeposite.setTradeType(TradeType.UNFROZEN_PAY);
			paramsVO.setBizType(AccountConstants.ACCOUNT_DJ_ZF);
			accountLog.setLogType(AccountConstants.ACCOUNT_DJ_ZF);
			recDeposite.setRemark("客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
			paramsVO.setRemark("冻结转支付（个人账户退款）" + "客户名称：[" + customerEntity.getCustomerName() + "],退款流程编号{[" + o2oBackFees.getBillCode() + "]}");
		}

		recDeposite.setAmount(o2oBackFees.getBackMoney());
		// 冻结
		recDeposite.setRollInAccount(customerEntity.getAccountId());// 转出账户
		// recDeposite.setRollOutAccount(loanapplyAccountEntity.getAccountNo());//
		// 转入账户
		recDeposite.setTradeBankcardNoIn("");// 本方交易银行卡号
		recDeposite.setTradeBankcardNoOut("");// 对方交易银行卡号
		recDeposite.setTradeDate(new Date());

		List<TradeDetailVO> detailsVO = new ArrayList<TradeDetailVO>();

		detailsVO.add(recDeposite);
		paramsVO.setBizId(o2oBackFees.getId());

		paramsVO.setDetails(detailsVO);
		paramsVO.setUniqueId(o2oBackFees.getUniqueId());

		paramsVO.setRequestId(accountLog.getId());
		paramsVO.setSource(SourceType.WEB);

		ModelResult<String> result = null;
		try {
			logger.info("调用个人账户退款接口开始，参数：【{}】", JSONObject.toJSONString(paramsVO));
			result = iFeeService.fee(paramsVO);

			logger.info("调用个人账户退款接口结束，成功与否：{},【信息：{}】", result.isSuccess(), result.getErrMsg());

			if (result.isSuccess()) {// 如果调用成功
				// updateLoanapplyExpand(expand, status);
				logger.info("调用service账号接口结束");
				return "SUCCESS";
			} else {
				return result.getErrCode();
			}
		} catch (Exception e) {
			logger.error("调用个人账户退款接口失败，失败信息为：{}", e.getMessage());
			return "个人账户退款失败";
			// throw new RuntimeException("个人账户退款失败");
		} finally {
			logger.info("ChargingDJ插入日志表开始========");
			accountLog.setStatus(String.valueOf(result.isSuccess()));
			accountLog.setEndTime(new Date());
			accountLog.setRequestid(o2oBackFees.getId());
			accountLog.setRequestPs(JSONObject.toJSONString(paramsVO));
			accountLog.setResponsePs(JSONObject.toJSONString(result));
			accountLog.setClassname(this.getClass().getName());
			accountLog.setLoanapplyNo(o2oBackFees.getId());
			accountLog.setMethodname(Thread.currentThread().getStackTrace()[1].getMethodName());
			iAccountLogService.add(accountLog);
			logger.info("ChargingDJ插入日志表结束========");
		}
	}

}
